<template>
    <div v-if="userInfo">
        <input type="file" class="file" ref="file" @change="changeAvatar">
        <el-avatar
            v-if="userInfo.avatar"
            :src="userInfo.avatar.replace(/public/,baseURL)"
            @click="clickChangeAvatar"
            shape="circle "
        />
        <el-avatar
            v-else
            :src="src"
            @click="clickChangeAvatar"
        />
    </div>
    
</template>
<script>
import {onMounted,toRefs,reactive,getCurrentInstance,ref,computed} from 'vue' ;
import {useStore} from 'vuex' ; 
import {ajax} from '@/api' ; 
import {baseURL} from '@/api/request' ; 
export default {
    setup(props){   
        const state = reactive({
            src:"https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
            baseURL,
        });
        const store = useStore();
        const file = ref(); 
        const userInfo = computed(()=>store.state.userInfo);
        const {proxy} = getCurrentInstance(); 
        const clickChangeAvatar = ()=>{
            file.value.click();
        }
        const changeAvatar = async ()=>{
            const filedata = file.value.files[0] ; 
            console.log(filedata);
            let form = new FormData();
            form.append('file',filedata);
            let {path} = await ajax.uploadfiles(form); 
            let {code,data} = await ajax.changeUser({
                avatar:path
            });
            if( code == 200 ){
                store.commit('updUserInfo',{
                    ...store.state.userInfo,avatar:path
                });
            }
        }
        onMounted(()=>{

        });
        return {
            ...toRefs(state),
            changeAvatar,
            clickChangeAvatar,
            userInfo,
            file
        }
    }
}
</script>
<style lang="scss" scoped>
.file{
    display: none;
}
.el-avatar{
    display: flex;
    justify-content: center;
    width: 100%;
    align-items: center;
    border-radius: 0;
    height: 50px;
    img{
        border-radius: 50%;
        width: 50px;
        height:50px;
    }
}
</style>